package com.qd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.qd.entity.*;
import com.qd.mapper.CartMapper;
import com.qd.mapper.OrderDetailMapper;
import com.qd.mapper.OrdersMapper;
import com.qd.mapper.ProductMapper;
import com.qd.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huangshuaikang
 * @since 2024-10-18
 */
@Service
public class OrdersServiceImpl extends MPJBaseServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired(required = false)
    OrdersMapper mapper;

    @Autowired(required = false)
    CartMapper cartMapper;

    @Autowired(required = false)
    OrderDetailMapper orderDetailMapper;

    @Autowired(required = false)
    ProductMapper productMapper;

    @Override
    public List<Orders> getList(OrderDto orders) {
        return mapper.getList(orders);
    }

    @Override
    public boolean addOrderAndDetail(Orders order) {
        //1.插入到订单表
        int insert =mapper.insert(order);

        //2.循环插入到详情表
        List<Cart> list = cartMapper.getList(order.getDeskId());
        OrderDetail od =new OrderDetail();
        for (Cart c:list){
            od.setOrderId(order.getId());
            od.setProName(c.getPname());
            od.setProPrice(c.getPrice());
            od.setProImg(c.getImg());
            od.setNum(c.getNum());
            orderDetailMapper.insert(od);

            Product product = productMapper.selectById(c.getPid());
            product.setSaleMonth(product.getSaleMonth()+c.getNum());
            productMapper.updateById(product);
        }

        //3.删除该桌对应的购物车信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",order.getDeskId());
        int delete =cartMapper.delete(queryWrapper);

        if(insert>0 && delete>0){
            return true;
        }
        return false;
    }
}
